import {message} from "antd";
import {getPhotoFromServer} from "@/api/PhotoApi";
import {RandomLocator} from './RandomLocator.ts'

class PhotoControl {
    private containerIndex: number;
    public index: number;
    public photoInfo: [{ name: string; size: number } | undefined];
    private readonly updateFnList: (() => void)[]
    private readonly randomLocator: RandomLocator

    constructor() {
        this.containerIndex = 0
        this.index = 0
        this.updateFnList = []
        this.randomLocator = new RandomLocator()
    }

    private currentSize() {
        return this.photoInfo[this.containerIndex].size
    }

    // 将更新函数添加到队列
    public addToUpdate(func: () => void) {
        this.updateFnList.push(func)
    }

    // 更新参数时，运行所有更新函数
    private update() {
        for (let fn of this.updateFnList) {
            fn()
        }
    }

    private showChangeContainerMessage() {
        message.info(this.photoInfo[this.containerIndex].name).then()
    }

    // 当容器索引变化时初始化图片定位器
    private initPhotoLocator() {
        this.randomLocator.init(this.photoInfo[this.containerIndex].size)
    }

    // 初始化
    public init(photoInfo: [{name: string; size: number}], containerIndex: number) {
        this.photoInfo = photoInfo
        this.containerIndex = containerIndex
        this.updateContainer()
    }

    // 设置下一张图片并更新图片定位器
    public updateContainer() {
        this.containerIndex++
        if (this.containerIndex >= this.photoInfo.length) {
            this.containerIndex = 0
        }
        this.initPhotoLocator()
        this.index = this.randomLocator.pop()
    }

    // 根据当前参数获取图片
    public async getPhoto(): Promise<Blob> {
        return await getPhotoFromServer(this.containerIndex, this.index)
    }

    // 下一张图片
    public next() {
        this.index = this.randomLocator.pop()
        if (this.index == -1) {
            this.updateContainer()
            this.showChangeContainerMessage()
        }
        this.update()
    }

    // 随机下一张图片
    public randomNext() {
        this.index = this.randomLocator.randomPop()
        if (this.index == -1) {
            this.updateContainer()
            this.showChangeContainerMessage()
        }
        this.update()
    }

    // 设置下一个容器
    public setContainer(containerIndex: number) {
        if (containerIndex < 0 || containerIndex >= this.photoInfo.length) {
            throw "参数错误：containerIndex = " + containerIndex
        }
        this.containerIndex = containerIndex
        this.index = 0
        this.updateContainer()
        this.showChangeContainerMessage()
        this.update()
    }

    // 获取容器
    public getContainer() {
        return this.containerIndex
    }
}

export default new PhotoControl()